import type { PropType } from 'vue'
import { computed, defineComponent, ref } from 'vue'
import { ElButton, ElForm, ElFormItem } from 'element-plus'
import { breakpointsTailwind, isFunction, useElementSize } from '@vueuse/core'
import Render from './render'
import type { QueryFormField } from '@/components/QueryForm/types'

export default defineComponent({
  props: {
    form: {
      type: Object as PropType<Record<string, any>>,
      required: true,
    },
    fields: {
      type: Array as PropType<QueryFormField<string>[]>,
      required: true,
    },
  },
  emits: ['update:form', 'search', 'rest'],
  setup(props, { emit }) {
    const containerRef = ref<HTMLDivElement | null>(null)
    const { width } = useElementSize(containerRef)
    const cols = computed(() => {
      if (width.value <= breakpointsTailwind.sm)
        return 1
      if (width.value <= breakpointsTailwind.md)
        return 2
      if (width.value <= breakpointsTailwind.lg)
        return 3
      if (width.value <= breakpointsTailwind.xl)
        return 4
      if (width.value > breakpointsTailwind.xl)
        return 5
      return 1
    })
    const expand = ref(false)
    const computedFields = computed(() => {
      return expand.value ? props.fields : props.fields.slice(0, cols.value - 1)
    },

    )
    const handleExpand = () => {
      expand.value = !expand.value
    }
    const update = (val: any, key: string) => {
      emit('update:form', { ...props.form, [key]: val })
    }
    const handleSearch = () => emit('search')
    const handleRest = () => emit('rest')
    return () => (
      <ElForm class="w-full" model={props.form}>
        <div class="grid gap-2 w-full" style={`grid-template-columns: repeat(${cols.value}, minmax(0, 1fr))`} ref={containerRef}>
          {
            computedFields.value.map(item => (
              <ElFormItem prop={item.key} key={item.key}>
                {{
                  default: () => <Render form={props.form} field={item} emit={(val: any) => update(val, item.key)} />,
                  label: () => isFunction(item.title) ? item.title() : item.title,
                }}
              </ElFormItem>
            ))
          }
          <ElFormItem class="col-start-auto col-end-[-1] place-self-center">
            {cols.value <= props.fields.length && <ElButton icon="Switch" circle onClick={handleExpand} />}
            <ElButton type="primary" icon="Search" onClick={handleSearch}>
              搜索
            </ElButton>
            <ElButton icon="Refresh" onClick={handleRest}>
              重置
            </ElButton>
          </ElFormItem>
        </div>
      </ElForm>
    )
  },
})
